<?php
/*
 * by: PhpStorm
 * 2021/7/23
 * 21:40
 * User: jweicao@qq.com
 */
namespace App\Api\Controllers;

use App\Api\Manages\CommonController;
use App\Api\Models\Member;
use App\Api\Models\QqAccount;
use App\Api\Repositories\ApiFace;
use App\Api\Repositories\BargainBasic;
use App\Api\Services\BlackWhite;
use App\Api\Services\JsonService;
use App\Api\Services\Token;
use App\Api\Services\UniqueStr;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;


class LoginController extends Controller
{
    /**
     * 手机号登录
     * @param Request $request
     * @return array
     */
    public function phoneLogin(Request $request)
    {

        try {
            $params = $this->validate($request, [
                'phone' => 'required|mobile',
                'password' => 'required|alpha_dash|min:6|max:16'
            ]);
        } catch (ValidationException $validationException) {
            $errors = $validationException->errors();
            return JsonService::fail(array_shift($errors)[0]);
        }
        try {
            list($phone, $pwd) = array_values($params);
            $pwd = CommonController::encrypt($pwd);
            $model = Member::login($phone, $pwd);
            if (!$model) return JsonService::fail('账号或密码有误');
            $ip = BlackWhite::getClientIp();
            $model->setAttribute('login_ip', $ip);
            $token = Token::MakeToken(['member_id' => $model->member_id]);
            return JsonService::success('登录成功', ['member_id' => $model->member_id, 'token' => $token]);
        } catch (\Exception $exception) {
            return JsonService::fail($exception->getMessage());
        }

    }

    /**
     * QQ登录
     * @param Request $request
     * @return array
     */
    public function qqCallback(Request $request)
    {

        try {
            $params = $this->validate($request, [
                'access_token' => 'required|unique:cmc_qq_accounts,access_token',
                'openid' => 'required|unique:cmc_qq_accounts,openid',
                'userinfo' => 'required|json',
            ]);
        } catch (ValidationException $validationException) {
            $errors = $validationException->errors();
            return JsonService::fail(array_shift($errors)[0]);
        }
        if (empty($params['access_token']) || empty($params['openid']) || empty($params['userinfo'])) {
            return JsonService::fail('参数不完整');
        }
        $data = [
            'access_token' => $params['access_token'],
            'openid' => $params['openid'],
            'userinfo' => $params['userinfo'],
        ];

        $model = QqAccount::saveData($data);
        if (!$model) return JsonService::fail('信息保存失败');
        return JsonService::success('qq登录成功', ['status' => 1],config('code.HTTP_OK'));

    }

    /**
     * 绑定手机号码
     * @param Request $request
     * @return array
     */
    public function bindPhone(Request $request)
    {
        try {
            $params = $this->validate($request, [
                'phone' => 'required|mobile',
                'openid' => 'required',
            ]);
        } catch (ValidationException $validationException) {
            $errors = $validationException->errors();
            return JsonService::fail(array_shift($errors)[0]);
        }
        if (empty($params['openid']) || empty($params['phone'])) {
            return JsonService::fail('参数不完整');
        }
        $memberId = Member::getMemberId(['phone' => $params['phone']]);
        if (!$memberId) {
            $username = UniqueStr::uniqueId();
            $password = CommonController::encrypt('123456');
            $data = [
                'username' => $username,
                'nickname' => $username,
                'password' => $password,
                'phone' => $params['phone'],
                'status' => 1
            ];
            $memberId = Member::saveData($data);
        }
        $data = [
            'member_id' => $memberId,
            'status' => 2
        ];
        $result = QqAccount::saveData($data, ['openid' => $params['openid']]);
        if (!$result) return JsonService::fail('关联失败');
        return JsonService::success('关联成功');
    }

    /**
     * 人脸识别登录
     * @param Request $request
     * @return array
     */
    public function faceLogin(Request $request)
    {

        try {
            $params = $this->validate($request, [
                'file' => 'required|image',
            ]);
        } catch (ValidationException $validationException) {
            $errors = $validationException->errors();
            return JsonService::fail(array_shift($errors)[0]);
        }

        $path = $params['file']->getRealPath();
        $baseImg = base64_encode(file_get_contents($path));
        $result = ApiFace::searchFace($baseImg);
        if ($result && $result['error_code'] == 0) {
            $userInfo = $result['result']['user_list'][0];
            $token = Token::MakeToken(['member_id'=>$userInfo['user_id']]);
            $data = [
                'member_id'=>$userInfo['user_id'],
                'token' => $token
            ];
            return JsonService::success('登录成功',$data);
        } else {
            return JsonService::fail('登陆失败');
        }
    }

    /**
     * 退出登录
     * @param Request $request
     */
    public function logout(Request $request)
    {
        $request->tokenData()->delete();
        return JsonService::success('登录成功');
    }

}
